﻿using System;
using System.Collections.Generic;
using YJKSparseDistance.ModelLayer;

namespace YJKSparseDistance.ControlLayer
{
	public class AsyncShortDistanceCalculateManger
	{
		public AsyncShortDistanceCalculateManger()
		{
			for (int i = 0; i <= this.m_nAsyncCount; i++)
			{
				this.m_lstTaskDelegate.Add(new AsyncShortDistanceDelegate(this.DelegateMethodCalculate));
			}
		}

		internal void SetTaskes(List<ShortDistacneCalculateBean> input)
		{
			this.m_lstTaskBean.AddRange(input);
		}

		public void Do()
		{
			if (this.m_lstTaskBean != null && this.m_lstTaskBean.Count != 0)
			{
				while (!this.IfFinal())
				{
				}
			}
		}

		public List<List<ResultBean>> GetAllResult()
		{
			List<List<ResultBean>> list = new List<List<ResultBean>>();
			foreach (ShortDistacneCalculateBean shortDistacneCalculateBean in this.m_lstTaskBean)
			{
				list.Add(shortDistacneCalculateBean.LstResultBean);
			}
			return list;
		}

		private void PrepareDelegate()
		{
			this.PassTask();
		}

		private void PassTask()
		{
			this.m_lstAllResult = new List<IAsyncResult>();
			foreach (AsyncShortDistanceDelegate asyncShortDistanceDelegate in this.m_lstTaskDelegate)
			{
				if (this.m_nNowBeanIndex < this.m_lstTaskBean.Count)
				{
					this.m_lstAllResult.Add(asyncShortDistanceDelegate.BeginInvoke(this.m_lstTaskBean[this.m_nNowBeanIndex], null, null));
					this.m_nNowBeanIndex++;
				}
			}
		}

		private bool IfFinal()
		{
			bool flag = true;
			foreach (IAsyncResult asyncResult in this.m_lstAllResult)
			{
				flag = (flag && asyncResult.IsCompleted);
			}
			if (!flag)
			{
				return false;
			}
			if (this.m_nNowBeanIndex >= this.m_lstTaskBean.Count)
			{
				return true;
			}
			this.PrepareDelegate();
			return false;
		}

		private void DelegateMethodCalculate(ShortDistacneCalculateBean inputValue)
		{
			inputValue.Calculate();
		}

		private List<ShortDistacneCalculateBean> m_lstTaskBean = new List<ShortDistacneCalculateBean>();

		private int m_nAsyncCount = 6;

		private int m_nNowBeanIndex;

		private List<AsyncShortDistanceDelegate> m_lstTaskDelegate = new List<AsyncShortDistanceDelegate>();

		private List<IAsyncResult> m_lstAllResult = new List<IAsyncResult>();
	}
}
